package com.huyn.sdktest;

import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by huyaonan on 16/10/27.
 */
public class AubeDatabaseHelper {

    private static AubeDatabaseHelper mInstance;
    private AubeDatabase mHelper;

    private static final String TABLE_NAME = "t_statistic";

    private AubeDatabaseHelper(Context context) {
        mHelper = new AubeDatabase(context, "aubesdk.db", null, 1);
    }

    public static synchronized AubeDatabaseHelper getInstance(Context context) {
        if(mInstance == null) {
            mInstance = new AubeDatabaseHelper(context);
        }
        return mInstance;
    }

    public void report(String key, String value) {
        SQLiteDatabase db = mHelper.getWritableDatabase();
        db.execSQL("insert into " + TABLE_NAME + "(key, value) values(?,?)", new Object[]{key, value});
        db.close();
    }

    /**
     * WARNING!!!
     * DO IT ASYNCHRONOUSLY
     */
    public String export() throws JSONException {
        JSONObject result = new JSONObject();
        SQLiteDatabase db = mHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select key, value, count(key) as count_key from " + TABLE_NAME + " group by key, value", null);
        if(cursor != null) {
            JSONArray data = new JSONArray();
            while (cursor.moveToNext()) {
                int count = cursor.getInt(2);
                String key = cursor.getString(0);
                String value = cursor.getString(1);

                JSONObject item = new JSONObject();
                item.put("key", key);
                item.put("value", value);
                item.put("count", count);
                data.put(item);
            }
            cursor.close();
            result.put("data", data);
            result.put("time", System.currentTimeMillis());
        }
        db.close();
        return result.toString();
    }

    private class AubeDatabase extends SQLiteOpenHelper {

        public AubeDatabase(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        public AubeDatabase(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
            super(context, name, factory, version, errorHandler);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("create table t_statistic(id integer primary key autoincrement,key varchar(200),value varchar(200) )");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }
    }

}
